package com.main;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import com.bo.DataSourceBean;

/**
 * 多租户多数据源批量执行
 * @Copyright: Copyright (c) 2017
 * @author zhengs
 */
public class ExecuteMulDBSql {
	private String jdbcDriver;
	
	private String url;
	
	private String userName;
	
	private String password;
	
	private Connection conn;
	
	private Statement stmt;
	
	private static final String SQL_FILE = "sqlBatch.sql";
	
	public void initParam(String paramFile) throws Exception{
		Properties prop=new Properties();
		prop.load(new FileInputStream(paramFile));
		jdbcDriver=prop.getProperty("jdbc.driver");
		url=prop.getProperty("jdbc.url");
		userName=prop.getProperty("jdbc.username");
		password=prop.getProperty("jdbc.password");
	}
	public List<DataSourceBean> getMulDataSource(String sql)throws Exception{
		List<DataSourceBean> list = new ArrayList<DataSourceBean>();
		
		try {
			Class.forName(jdbcDriver);
			conn=DriverManager.getConnection(url,userName,password);
			stmt=conn.createStatement();
			
		    ResultSet rs = stmt.executeQuery(sql);
		    while (rs.next()) {
		        list.add(new DataSourceBean(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)));
		    }
		} finally{
			if(stmt!=null){
				stmt.close();
			}
			if(conn!=null){
				conn.close();
			}
		}
		
		return list;
	}
	
	public void executeSqlFile(String driver, String url , String username, String password, String sqlFile)throws Exception{
		try {
			Class.forName(driver);
			conn=DriverManager.getConnection(url,username,password);
			stmt=conn.createStatement();
			
			ScriptRunner runner=new ScriptRunner(conn);
			runner.runScript(Resources.getResourceAsReader(sqlFile));
		}
		catch(Exception e){
		}
		finally{
			if(stmt!=null)
				stmt.close();
			if(conn!=null)
				conn.close();
		}
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println("---------开始执行-------");
		ExecuteMulDBSql executeMulDBSql = new ExecuteMulDBSql();
		
		executeMulDBSql.initParam("src/jdbc.properties");

	    String sql = "select driver_class_name,url,username,password from sys_datasource";
	    List<DataSourceBean> list = executeMulDBSql.getMulDataSource(sql);
	    
	    for(DataSourceBean bean : list){
	    	System.out.println(bean.getUrl());
	    	executeMulDBSql.executeSqlFile(bean.getJdbcDriver(), bean.getUrl(), bean.getUserName(), bean.getPassword(), SQL_FILE);
	    }
	    
		System.out.println("---------执行完成-------");
	}

}